import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../constants/app_constants.dart';
import '../storage/storage_service.dart';
import '../utils/logger.dart';
import '../../shared/services/auth_service.dart';
import 'base_controller.dart';

class GlobalController extends BaseController {
  static GlobalController get instance => Get.find<GlobalController>();
  
  final StorageService _storageService = StorageService.instance;
  final AuthService _authService = AuthService.instance;
  
  // 主题相关
  final _themeMode = ThemeMode.system.obs;
  ThemeMode get themeMode => _themeMode.value;
  
  final _isDarkMode = false.obs;
  bool get isDarkMode => _isDarkMode.value;
  
  // 语言相关
  final _locale = const Locale('zh', 'CN').obs;
  Locale get locale => _locale.value;
  
  // 应用设置
  final _appSettings = <String, dynamic>{}.obs;
  Map<String, dynamic> get appSettings => _appSettings;
  
  // 用户偏好设置
  final _userPreferences = <String, dynamic>{}.obs;
  Map<String, dynamic> get userPreferences => _userPreferences;
  
  // 网络状态
  final _isOnline = true.obs;
  bool get isOnline => _isOnline.value;
  
  // 应用状态
  final _isInitialized = false.obs;
  bool get isInitialized => _isInitialized.value;
  
  // 加载状态
  final _isAppLoading = false.obs;
  bool get isAppLoading => _isAppLoading.value;
  
  // 首次启动
  final _isFirstLaunch = true.obs;
  bool get isFirstLaunch => _isFirstLaunch.value;
  
  // 应用版本
  final _appVersion = ''.obs;
  String get appVersion => _appVersion.value;
  
  // 设备信息
  final _deviceInfo = <String, dynamic>{}.obs;
  Map<String, dynamic> get deviceInfo => _deviceInfo;
  
  @override
  void onInit() {
    super.onInit();
    initializeApp();
  }
  
  // 初始化应用
  Future<void> initializeApp() async {
    try {
      _isAppLoading.value = true;
      
      // 加载用户偏好设置
      await _loadUserPreferences();
      
      // 加载应用设置
      await _loadAppSettings();
      
      // 初始化主题
      await _initializeTheme();
      
      // 初始化语言
      await _initializeLocale();
      
      // 检查首次启动
      await _checkFirstLaunch();
      
      // 加载设备信息
      await _loadDeviceInfo();
      
      // 获取应用版本
      await _loadAppVersion();
      
      _isInitialized.value = true;
      _isAppLoading.value = false;
      
      AppLogger.info('Global controller initialized');
    } catch (e) {
      _isAppLoading.value = false;
      AppLogger.error('Failed to initialize global controller', e);
    }
  }
  
  // 加载用户偏好设置
  Future<void> _loadUserPreferences() async {
    try {
      final prefs = _storageService.getUserPreference<Map<String, dynamic>>(
        'user_preferences',
        {},
      );
      _userPreferences.value = prefs ?? {};
    } catch (e) {
      AppLogger.error('Failed to load user preferences', e);
    }
  }
  
  // 保存用户偏好设置
  Future<void> saveUserPreferences() async {
    try {
      await _storageService.setUserPreference('user_preferences', _userPreferences);
    } catch (e) {
      AppLogger.error('Failed to save user preferences', e);
    }
  }
  
  // 加载应用设置
  Future<void> _loadAppSettings() async {
    try {
      final settings = _storageService.getUserPreference<Map<String, dynamic>>(
        'app_settings',
        {},
      );
      _appSettings.value = settings ?? {};
    } catch (e) {
      AppLogger.error('Failed to load app settings', e);
    }
  }
  
  // 保存应用设置
  Future<void> saveAppSettings() async {
    try {
      await _storageService.setUserPreference('app_settings', _appSettings);
    } catch (e) {
      AppLogger.error('Failed to save app settings', e);
    }
  }
  
  // 初始化主题
  Future<void> _initializeTheme() async {
    try {
      final savedTheme = _storageService.getUserPreference<String>(
        AppConstants.themeKey,
        'system',
      );
      
      switch (savedTheme) {
        case 'light':
          _themeMode.value = ThemeMode.light;
          break;
        case 'dark':
          _themeMode.value = ThemeMode.dark;
          break;
        default:
          _themeMode.value = ThemeMode.system;
      }
      
      _updateDarkModeStatus();
    } catch (e) {
      AppLogger.error('Failed to initialize theme', e);
    }
  }
  
  // 更新暗黑模式状态
  void _updateDarkModeStatus() {
    final brightness = Get.mediaQuery.platformBrightness;
    switch (_themeMode.value) {
      case ThemeMode.light:
        _isDarkMode.value = false;
        break;
      case ThemeMode.dark:
        _isDarkMode.value = true;
        break;
      case ThemeMode.system:
        _isDarkMode.value = brightness == Brightness.dark;
        break;
    }
  }
  
  // 设置主题模式
  Future<void> setThemeMode(ThemeMode mode) async {
    try {
      _themeMode.value = mode;
      _updateDarkModeStatus();
      
      String themeString;
      switch (mode) {
        case ThemeMode.light:
          themeString = 'light';
          break;
        case ThemeMode.dark:
          themeString = 'dark';
          break;
        case ThemeMode.system:
          themeString = 'system';
          break;
      }
      
      await _storageService.setUserPreference(AppConstants.themeKey, themeString);
      Get.changeThemeMode(mode);
      
      AppLogger.info('Theme mode changed to: $themeString');
    } catch (e) {
      AppLogger.error('Failed to set theme mode', e);
    }
  }
  
  // 切换主题
  Future<void> toggleTheme() async {
    final newMode = _isDarkMode.value ? ThemeMode.light : ThemeMode.dark;
    await setThemeMode(newMode);
  }
  
  // 初始化语言
  Future<void> _initializeLocale() async {
    try {
      final savedLanguage = _storageService.getUserPreference<String>(
        AppConstants.languageKey,
        'zh_CN',
      );
      
      final parts = savedLanguage?.split('_') ?? ['zh', 'CN'];
      _locale.value = Locale(parts[0], parts.length > 1 ? parts[1] : null);
    } catch (e) {
      AppLogger.error('Failed to initialize locale', e);
    }
  }
  
  // 设置语言
  Future<void> setLocale(Locale locale) async {
    try {
      _locale.value = locale;
      final languageCode = '${locale.languageCode}_${locale.countryCode ?? ''}';
      await _storageService.setUserPreference(AppConstants.languageKey, languageCode);
      
      Get.updateLocale(locale);
      AppLogger.info('Locale changed to: $languageCode');
    } catch (e) {
      AppLogger.error('Failed to set locale', e);
    }
  }
  
  // 检查首次启动
  Future<void> _checkFirstLaunch() async {
    try {
      final isFirst = _storageService.getUserPreference<bool>('is_first_launch', true);
      _isFirstLaunch.value = isFirst ?? true;
      
      if (_isFirstLaunch.value) {
        // 首次启动，保存标记
        await _storageService.setUserPreference('is_first_launch', false);
      }
    } catch (e) {
      AppLogger.error('Failed to check first launch', e);
    }
  }
  
  // 加载设备信息
  Future<void> _loadDeviceInfo() async {
    try {
      // 这里可以使用device_info_plus包获取设备信息
      _deviceInfo.value = {
        'platform': GetPlatform.isAndroid ? 'android' : GetPlatform.isIOS ? 'ios' : 'unknown',
        'isWeb': GetPlatform.isWeb,
        'isMobile': GetPlatform.isMobile,
        'isDesktop': GetPlatform.isDesktop,
      };
    } catch (e) {
      AppLogger.error('Failed to load device info', e);
    }
  }
  
  // 加载应用版本
  Future<void> _loadAppVersion() async {
    try {
      // 这里可以使用package_info_plus包获取应用版本
      _appVersion.value = AppConstants.appVersion;
    } catch (e) {
      AppLogger.error('Failed to load app version', e);
    }
  }
  
  // 设置网络状态
  void setOnlineStatus(bool isOnline) {
    _isOnline.value = isOnline;
    AppLogger.info('Network status changed: ${isOnline ? 'online' : 'offline'}');
  }
  
  // 获取用户偏好设置
  T? getUserPreference<T>(String key, [T? defaultValue]) {
    return _userPreferences[key] as T? ?? defaultValue;
  }
  
  // 设置用户偏好设置
  void setUserPreference(String key, dynamic value) {
    _userPreferences[key] = value;
    saveUserPreferences();
  }
  
  // 获取应用设置
  T? getAppSetting<T>(String key, [T? defaultValue]) {
    return _appSettings[key] as T? ?? defaultValue;
  }
  
  // 设置应用设置
  void setAppSetting(String key, dynamic value) {
    _appSettings[key] = value;
    saveAppSettings();
  }
  
  // 重置应用设置
  Future<void> resetAppSettings() async {
    try {
      _appSettings.clear();
      await saveAppSettings();
      AppLogger.info('App settings reset');
    } catch (e) {
      AppLogger.error('Failed to reset app settings', e);
    }
  }
  
  // 重置用户偏好设置
  Future<void> resetUserPreferences() async {
    try {
      _userPreferences.clear();
      await saveUserPreferences();
      AppLogger.info('User preferences reset');
    } catch (e) {
      AppLogger.error('Failed to reset user preferences', e);
    }
  }
  
  // 清除所有数据
  Future<void> clearAllData() async {
    try {
      await _storageService.clearUserPreferences();
      await _storageService.clearCache();
      await _authService.clearToken();
      
      _appSettings.clear();
      _userPreferences.clear();
      _isFirstLaunch.value = true;
      
      AppLogger.info('All data cleared');
    } catch (e) {
      AppLogger.error('Failed to clear all data', e);
    }
  }
  
  // 获取全局状态
  Map<String, dynamic> get globalState => {
    'themeMode': _themeMode.value.toString(),
    'isDarkMode': _isDarkMode.value,
    'locale': _locale.value.toString(),
    'isOnline': _isOnline.value,
    'isInitialized': _isInitialized.value,
    'isAppLoading': _isAppLoading.value,
    'isFirstLaunch': _isFirstLaunch.value,
    'appVersion': _appVersion.value,
    'deviceInfo': _deviceInfo,
    'appSettings': _appSettings,
    'userPreferences': _userPreferences,
  };
  
  // 调试信息
  void printDebugInfo() {
    AppLogger.debug('=== Global Controller Debug Info ===');
    AppLogger.debug('Theme Mode: ${_themeMode.value}');
    AppLogger.debug('Is Dark Mode: ${_isDarkMode.value}');
    AppLogger.debug('Locale: ${_locale.value}');
    AppLogger.debug('Is Online: ${_isOnline.value}');
    AppLogger.debug('Is Initialized: ${_isInitialized.value}');
    AppLogger.debug('Is App Loading: ${_isAppLoading.value}');
    AppLogger.debug('Is First Launch: ${_isFirstLaunch.value}');
    AppLogger.debug('App Version: ${_appVersion.value}');
    AppLogger.debug('Device Info: ${_deviceInfo}');
    AppLogger.debug('App Settings: ${_appSettings}');
    AppLogger.debug('User Preferences: ${_userPreferences}');
    AppLogger.debug('=====================================');
  }
}